<template>
	<view>
		<!-- 未登录状态 -->
		<view class="login-hezi">
			<view class="login-nh">
				<image src="/static/default-avatar.png"></image>
				<button class="butt" @click="getUserInfo">一键登录</button>
				<text class="wenb">登录后尽享更多功能</text>
			</view>
		</view>
	</view>
</template>

<script>
import { mapState } from 'vuex'
	export default {
		name:"my-login",
		data() {
			return {
				token:'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NDM5NTYwNjYsImlhdCI6MTY0MzM1MTI2NiwidXNlcm5hbWUiOiIyMTU2MTY4Ny1lOTU2LTQ4OTEifQ.W_5lSwTu2SwrSQHWMzNiyFtpkkcaWg2fx8DgxlVTpoQ'
			};
		},
		computed:{
			...mapState({Router:state=>state.user.Router})
		},
		methods:{
			//点击登录事件
			getUserInfo(){
				//展示加载框
				uni.showLoading({
					title:'加载中',
				})
				//获取用户信息，调用登录接口、
				uni.getUserProfile({
					desc:'登录后可同步数据',
					//obj就是用户点击了确认返回的用户信息
					success:(obj)=>{
						//把用户信息保存至vuex，
						this.$store.commit('getaddlogin',obj)
						//获取code，并发送登录接口
						this.getToken(obj)
					},
					//点击了取消登录事件
					fail:()=>{
						uni.showToast({
							title:'授权已取消',
							icon:'error',
							mask:true
						})
					},
					complete:()=>{
					   // 关闭加载框
					   uni.hideLoading()
					}
				})
			},
			//登录请求
			async getToken(obj){
				const [err,res] = await uni.login().catch(err=>err)
				if(!err || res.errMsg == "login:ok"){
					const query = {
						encryptedData:obj.encryptedData,
						rawData:obj.rawData,
						iv:obj.iv,
						code:res.code,
						signature:obj.signature
					}
					let { data:result } = await uni.$http.post('/users/wxlogin',query)
					if(result.meta.status == 400){
						uni.showToast({
							title:'登录成功',
							icon:'success',
							mask:true
						})
						this.$store.commit('getlogintoken',this.token)
						if(this.Router.from || this.Router.openType == 'switchTab'){
							uni.switchTab({
								url:this.Router.from,
								//跳转完成之后执行的函数
								complete:()=>{
									this.$store.commit('dieltrouets')
								}
							})
						}
					}else{
						uni.showToast({
							title:'登录失败,尝试重新登录看看~',
							icon:'error',
							mask:true
						})
					}
				}else{
					uni.showToast({
						title:'获取CODE失败',
						icon:'error',
						mask:true
					})
				}
			}
		}
	}
</script>

<style lang="scss">
.login-hezi{
	display: flex;
	height: 500px;
	justify-content: center;
	align-items: center;
	.login-nh{
		display: flex;
		flex-direction: column;
		align-items: center;
		image{
			width: 124px;
			height: 124px;
		}
		.butt{
			margin: 20px 0 15px 0;
			width: 320px;
			border-radius: 24px;
			background: #00aaff;
		}
		.wenb{
			font-size: 13px;
			color: #6f6f6f;
		}
	}
}
</style>
